package org.sean.framework.redis;

import org.sean.framework.util.GSONType;
import org.sean.framework.util.GSONUtil;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.lang.reflect.Type;

/**
 * 使用Gson处理的 Redis编码类
 *
 * @param <T> T
 * @author Sean.xie
 */
public class GsonRedisSerializer<T> implements RedisSerializer<T> {

    private final Type javaType;


    /**
     * Creates a new {@link GsonRedisSerializer} for the given target {@link GSONType}.
     *
     * @param type 类型
     */
    public GsonRedisSerializer(Type type) {
        this.javaType = type;
    }


    /**
     * JSON 解码
     */
    @Override
    public T deserialize(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            return GSONUtil.json2Obj(new String(bytes), javaType);
        } catch (Exception ex) {
            throw new SerializationException("Could not read JSON: " + ex.getMessage(), ex);
        }
    }

    /**
     * JSON 编码
     */
    @Override
    public byte[] serialize(T t) {
        if (t == null) {
            return new byte[0];
        }
        try {
            return GSONUtil.obj2Json(t).getBytes();
        } catch (Exception ex) {
            throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }

}
